package com.rsscollector.controller.acegisecurity;

import java.util.Collection;
import java.util.Iterator;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;

import com.rsscollector.model.UserFacade;
import com.rsscollector.model.vo.Privilege;

public class UserDetailsServiceImpl implements UserDetailsService {

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

    	/* Load user from database */
        com.rsscollector.model.vo.User user = UserFacade.getUserByEmail(username);
        if (user == null) {
        	throw new UsernameNotFoundException("Cannot find a user with username=" + username);
        }
        
        /* Get user privileges */
        GrantedAuthority[] authorities;
        Collection privileges = user.getPrivileges();
        if (privileges == null || privileges.isEmpty()) {
        	authorities = new GrantedAuthority[0];
        } else {
        	authorities = new GrantedAuthority[privileges.size()];
        	int index = 0;
            for (Iterator it = user.getPrivileges().iterator(); it.hasNext();) {
    			Privilege priv = (Privilege) it.next();
    			authorities[index++] = new GrantedAuthorityImpl(priv.getName());
    		}
        }
        
        /* Build acegisecurity User object to return */
        User secuser = new User(user.getEmail(), user.getPassword(), 
        		!user.isAccountDisabled(), !user.isAccountExpired(), !user.isPasswordExpired(), 
        		!user.isAccountLocked(), authorities);
        
        return secuser;
    }
}
